package com.lovo.testjpa.service.impl;

import com.lovo.testjpa.bean.Role;
import com.lovo.testjpa.bean.User;
import com.lovo.testjpa.dao.UserDAO;
import com.lovo.testjpa.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDAO userDAO;

    @Override
    public List<User> listUser() {
        return userDAO.findAll();
    }

    @Override
    @Transactional
    public void add(User user) {
        userDAO.save(user);
    }

    @Override
    @Transactional
    public void assignUserRole(Integer id, Integer[] roleIds) {
        User user = userDAO.findById(id).get();
        ArrayList<Role> roles = new ArrayList();
        for(int i = 0;i < roleIds.length;i++){
            roles.add(new Role(roleIds[i]));
        }
        user.setRoles(roles);
        userDAO.save(user);

    }

    @Override
    public void delete(Integer id) {
        userDAO.deleteById(id);
    }
}
